import React from "react";
import { Route, Link, Redirect, Switch } from "react-router-dom";
import Loadable from 'react-loadable';

// 引入数据请求
import _getHomeMenu from '../containers/Home/load-data';

/**
 * 创建路由组件
 * @param {Object} param，在服务端渲染时注入的后台数据参数，可用于控制页面渲染
 * @return {{routeConfig, dom}}
 */
export default param => {
    /**
     * 下面的几个函数用于对用户进行权限校验或可以注入其他校验
     * 基本目的是对页面入口加以限制
     */
    // 需要登录用户才能访问的页面入口
    const requireAuth = (Layout, props) => {
        if(param.userinfo) {
            return <Layout {...props} />
        } else {
            // TODO 思考如何支持单点登录和全局登录组件
            return <Redirect to="/login" />
        }
    }

    // 无需权限校验的页面苦肉
    const triggerEnter = (Layout, props) => {
        return <Layout {...props} />
    }

    // 路由配置
    const routes = [
        {
            path: '/',
            exact: true,
            strict: false,
            component: Loadable({
                loader: () => import('@/client/containers/Home/index'),
                loading: () => <div>...loading</div>
            }),
            enter: triggerEnter,
            loadData: _getHomeMenu
        }, {
            path: '/repository',
            exact: true,
            strict: false,
            component: Loadable({
                loader: () => import('@/client/containers/Repository/index'),
                loading: () => <div>...loading</div>
            }),
            enter: triggerEnter
        }
    ]

    let router = () => (
        <div>
            <Switch>
                {routes.map((route, i) => {
                    return <Route key={i} path={route.path} exact={route.exact} component={props => route.enter(route.component, props)} />
                })}
            </Switch>
        </div>
    )

    return {
        routeConfig: routes,
        dom: router
    }
}